#!/usr/bin/env python
 
import Queue, threading, serial, signal
from time import sleep
class test:
	data_end=["ERROR","OK","RING","CONNECT","BUSY","NO DIALTONE","NO CARRIER"]
	def __init__(self):
		self.Qcommand = Queue.Queue(0)
		self.koniec = False
		self.seport = serial.Serial("/dev/ttyACM0", 115200, timeout=1)
		print "Connection: ",self.seport.isOpen()

	def start(self):
		thrd = threading.Thread(target=self.zober_z_fronty)
		thrd.start()
		thrd1 = threading.Thread(target=self.prijimaj_data)
		thrd1.start()

	def prijimaj_data(self):
		self.seport.open()
		command=""
		while not self.koniec:
			if self.seport.inWaiting() > 0:
				data = self.seport.read(self.seport.inWaiting())
				datalines=data.replace("\r\r","\r").rstrip("\r\n").split("\r\n")
				while len(datalines):
				    command+=datalines[0]+"\n"
				    if datalines[0] in self.data_end:
					self.Qcommand.put(command)
					command=''
				    datalines=datalines[1:]
				



			else:
				sleep(0.1)
		self.seport.close()

	def zober_z_fronty(self):
		data=""
		while not (self.koniec and self.Qcommand.empty()):
			if not self.Qcommand.empty():
				data = self.Qcommand.get()
				self.spracuj_data(data)
			else:
				sleep(0.1)

	def spracuj_data(self, data):
	    print data

	def zapis_data(self,data):
	    self.seport.write(data)

	def rinput(self):
#	    while not self.koniec:
		self.idata=raw_input(">")
		if self.idata == "/quit":
		    self.koniec = True
		else:
		    self.zapis_data(self.idata+"\r")


	def konec(self):
	    self.koniec = True
     



    
